package com.whater.wechat.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.whater.common.domain.AjaxResult;
import com.whater.common.util.StringUtils;
import com.whater.common.util.WxChatImgRevert2;
import com.whater.wechat.dao.ImagesDao;
import com.whater.wechat.entity.Images;
import com.whater.wechat.entity.Videos;
import com.whater.wechat.util.CommonUtil;
import com.whater.wechat.vo.ImageVo;
import com.whater.wechat.vo.PathVo;

@Service
public class ImageService {
	
	@Value("${wechat.image.path}")
	private String imagePath ;
	@Value("${wechat.backup.path}")
	private String backupPath;
	@Autowired
	private ImagesDao imagesDao ;
	
	public List<PathVo> getPath(String path){
		String realPath = imagePath ;
		if(StringUtils.isNotEmpty(path)) {
			realPath += "/"+ path;
		}
		return Arrays.asList(new File(realPath).listFiles()).stream().map(item->{
			return new PathVo(item.getAbsolutePath(),item.getName(),isDate(item.getName()));
		}).collect(Collectors.toList());
	}
	
	public AjaxResult getImage(String path,Integer skip,Integer limit,final boolean includeOptData,boolean  selectedData){
		String realPath = imagePath ;
		if(StringUtils.isNotEmpty(path)) {
			realPath += "/"+ path;
		}
		Images imagesExample = new Images();
		imagesExample.setSelected(true);
		Set<String> set = imagesDao.findAll(Example.of(imagesExample)).parallelStream().map(Images::getShortName).collect(Collectors.toSet());
		Set<String> allOptDate = new HashSet<>();
		if(!includeOptData) {
			allOptDate = imagesDao.findAll().parallelStream().map(Images::getShortName).collect(Collectors.toSet());
		}
		final Set<String> allOptDateEnd = allOptDate ;
		final AtomicInteger atomicInteger = new AtomicInteger(0);
		File file = new File(realPath) ;
		AjaxResult result = AjaxResult.success(Arrays.asList(file.listFiles()).stream().filter(e -> {
			if(selectedData) {
				return set.contains(e.getName()) ;
			}
			if(!includeOptData)
				atomicInteger.incrementAndGet();
			return includeOptData||!allOptDateEnd.contains(e.getName());
		}).skip(skip).limit(limit).map(item -> {
			return new ImageVo(item.getName(), item.lastModified(), set.contains(item.getName()));
		}).collect(Collectors.toList()));
		result.put("resultSkip", skip+atomicInteger.get());
		result.put("total", file.listFiles().length);
		return result;
	}
	
	public String getFullPath(String image) {
		String realPath = imagePath ;
		if(StringUtils.isNotEmpty(image)) {
			realPath += "/"+ image;
		}
		return realPath ;
	}
	public boolean isDate(String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd");
			sdf.parse(date);
		} catch (ParseException e) {
			return false;
		}
        return true;
	}
	@Transactional
	public AjaxResult submit(JSONArray data) {
		data.forEach(item->{
			Map<?, ?> jsonObject = (Map<?, ?>)item ;
			Images images = imagesDao.findByShortName(jsonObject.get("id").toString());
			if(images == null) {
				images =  new Images();
			}
			images.setCrtDate(new Date((Long)jsonObject.get("crtDate")));
			images.setShortName(jsonObject.get("id").toString());
			images.setPath(jsonObject.get("dir").toString());
			images.setFullPath(jsonObject.get("dir").toString()+"/"+jsonObject.get("id").toString());
			images.setSelected((Boolean)jsonObject.get("selected"));
			imagesDao.save(images);
		});
		return AjaxResult.success();
	}
	
	@Transactional
	public AjaxResult export(JSONArray data) {
		data.forEach(item -> {
			Map<?, ?> jsonObject = (Map<?, ?>) item;
			Images images = imagesDao.findByShortName(jsonObject.get("id").toString());
			if(images == null) {
				images =  new Images();
			}
			if(images.getExported() !=null && images.getExported()) {
				return;
			}
			images.setCrtDate(new Date((Long)jsonObject.get("crtDate")));
			images.setShortName(jsonObject.get("id").toString());
			images.setPath(jsonObject.get("dir").toString());
			images.setFullPath(jsonObject.get("dir").toString()+"/"+jsonObject.get("id").toString());
			images.setSelected((Boolean)jsonObject.get("selected"));
			OutputStream out = null ;
			try {
				File file = new File(backupPath+"/image/"+images.getFullPath()+".jpg");
				file.getParentFile().mkdirs();
				out = new FileOutputStream(file);
				WxChatImgRevert2.outImage(new File(getFullPath(images.getFullPath())), out);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}finally {
				if(out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			images.setExported(true);
			imagesDao.save(images);
		});
		return AjaxResult.success();
	}
}
